/*
 * LiveMediaPlayer.cpp
 *
 *  Created on: 2018年8月2日
 *      Author: zhengboyuan
 */
#include "stdafx.h"
#include "LiveMediaPlayer.h"
#include "TStringUtil.h"
#include "CLog.h"

int	LiveMediaPlayer::MAX_DELAY_TIME =  1000 * 1;


LiveMediaPlayer::LiveMediaPlayer():
    m_devID(),
    m_faceTrackEnabled(),
	m_faceCount()
{
}

LiveMediaPlayer::~LiveMediaPlayer()
{
    Close();
}

bool LiveMediaPlayer::Open(nvs::NetVideoSystem* system, const char* devID)
{
    if (!system || !devID)
    {
        return false;
    }

    m_devID = devID;

    nvs::MediaStream* stream = NULL;
    int ret = system->openLiveStream(devID, 0, &stream);
    if (ret != nvs::NVS_ERR_OK)
    {
		CLog::warning("LiveMediaPlayer::Open(%d). failed to open %s. ret: %d\n", m_id, devID, ret);
        return false;
    }

	CLog::info("LiveMediaPlayer::Open(%d). dev: %s, openLiveStream 0x%p\n", m_id, devID, stream);

    return MediaStreamPlayer::Open(system, stream);
}

bool LiveMediaPlayer::CanSeek()
{
    return false;
}

std::string LiveMediaPlayer::GetUrl()
{
    return m_devID;
}

void LiveMediaPlayer::EnableDrawTrack(bool enabled)
{
	comn::AutoCritSec lock(m_cs);
    m_faceTrackEnabled = enabled;

	if (IsOpen())
	{
		MDecode_SetDelayTime(m_handle, MAX_DELAY_TIME);
	}
}

void LiveMediaPlayer::onOpen()
{
	MediaStreamPlayer::onOpen();

	if (m_faceTrackEnabled)
	{
		MDecode_SetDelayTime(m_handle, MAX_DELAY_TIME);
	}
}

void LiveMediaPlayer::InputFaceTrack(const char* devID, const char* text, int size)
{
	if (!text || size <= 0)
	{
		return;
	}

	m_faceCount ++;

	std::string src(text, size);
	std::string fid = comn::StringUtil::extract(src, 0, "frame_id\":", ",", true);
	comn::StringUtil::trim(fid, ":\" ");

	int64_t pts = 0;
	comn::StringCast::toValue(fid, pts);

	int64_t ms = pts / 1000;
	CTime t(ms /1000);
	CString str = t.Format(TEXT("%d-%m-%y %H:%M:%S"));


	if (!m_faceTrackEnabled)
	{
		return;
	}

	MDecode_InputData(m_handle, MDECODE_MEDIA_SUBTITLE, (const uint8_t*)text, size, pts, 0);
}


int LiveMediaPlayer::writePacket(const nvs::StreamPacket& packet)
{
	if (packet.flag == nvs::IMS_FRAME_ALARM_ANALYZE)
	{
		InputFaceTrack(m_devID.c_str(),(const char *)packet.data,packet.size);
	}

	return MediaStreamPlayer::writePacket(packet);
}

void LiveMediaPlayer::endOfStream(int reason)
{
	CLog::info("LiveMediaPlayer::endOfStream(%d). dev: %s\n", m_id, m_devID.c_str());

	MediaStreamPlayer::endOfStream(reason);
}

bool LiveMediaPlayer::Reconnect(nvs::NetVideoSystem* system)
{
	CLog::info("LiveMediaPlayer::Reconnect(%d). dev: %s\n", m_id, m_devID.c_str());

	closeStream();

	if (!Open(system, m_devID.c_str()))
	{
		return false;
	}

	Play();

	return true;
}
